// 简化路径

package Leetcode;

import java.util.Deque;
import java.util.LinkedList;

class solution_071 {
    public static String simplifyPath(String path) {
        // 去除多余的斜杠
        String temp = new String();
        int sign = 0;
        int i = 0;
        for (int j = 0; j < path.length(); j++) {
            if (path.charAt(j) != '/') {
                i = j;
                break;
            }
        }
        for (; i < path.length(); i++) {
            char c = path.toCharArray()[i];
            if (c == '/' && sign == 0) {
                sign = 1;
                temp += c;
            }
            if (c != '/') {
                sign = 0;
                temp += c;
            }
        }
        // System.out.println(path);
        // System.out.println(temp);
        String[] element = temp.split("/");
        // for (String s : element)
        // for (char c : s.toCharArray())
        // System.out.println(c);
        // // 构造栈用于模拟路径
        Deque<String> stack = new LinkedList<>();
        for (String s : element) {
            if (s.compareTo("..") != 0 && s.compareTo(".") != 0)
                stack.push(s);
            else if (s.compareTo(".") == 0)
                continue;
            else if (s.compareTo("..") == 0) {
                if (stack.isEmpty())
                    continue;
                else
                    stack.pop();
            }
        }
        // 构造输出
        String result = new String();
        while (stack.isEmpty() == false) {
            // System.out.println(stack.peekLast());
            result = result + "/" + stack.peekLast();
            stack.removeLast();
        }
        return result.length() == 0 ? "/" : result;
    }

    public static void main(String[] args) {
        String s = "/../";
        simplifyPath(s);
    }
}


// 上述代码思路正确但是对函数的理解不当
public class Solution071 {
    public static String simplifyPath(String path) {
        String[] element = path.split("/");
        // for(String s : element)
        //     System.out.println(s + "@"+ s.equals(""));
        Deque<String> stack = new LinkedList<>();
        for (String str : element) {
            if (str.equals("..")) {
                if (stack.isEmpty() == false)
                    stack.pollLast();
            } else if (str.length() > 0 && !str.equals("."))
                stack.offerLast(str);
        }
        String result = new String();
        if (stack.isEmpty())
            return "/";
        else {
            while (stack.isEmpty() == false) {
                result = result + "/" + stack.pollFirst();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "/a/./b///..//../c/";
        simplifyPath(s);
    }
}
